package com.stdio.view;

import com.stdio.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.SectionIndexer;


public class AlphabetScrollBar extends View {

	private SectionIndexer mSectionIndexer = null;
	private ListView mListView = null;
	private float nItemHeight = 0.00f;
	private boolean bTouch = false;

	public AlphabetScrollBar(Context context) {
		super(context);
	}

	public AlphabetScrollBar(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public AlphabetScrollBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void setListView(ListView list) {
		mListView = list;
		mSectionIndexer = (SectionIndexer) list.getAdapter();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		int height = getHeight();
		int width = getWidth();
		nItemHeight = (float)height / (float)(sSignation.length);
		
		if(bTouch) {
			Drawable bg = this.getResources().getDrawable(
					R.drawable.search_bar_bg);
			bg.setBounds(0, 0, width, height);
			bg.draw(canvas);
		}

		Drawable search = this.getResources().getDrawable(
				R.drawable.scroll_bar_search_icon);
		search.setBounds(3, 3, 18, 18);
		search.draw(canvas);
		
		Paint paint = new Paint();
		paint.setColor(0xff888888);
		paint.setTextSize(11);
		paint.setTextAlign(Paint.Align.CENTER);
		paint.setAntiAlias(true);
		float widthCenter = (float)getMeasuredWidth() / 2;

		for (int i = 0; i < sSignation.length; i++) {
			canvas.drawText(String.valueOf(sSignation[i]), widthCenter,
					((i + 1) * nItemHeight), paint);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);
		float fy = event.getY();
		int index = 0;

		if (nItemHeight > 0) {
			index = (int) (fy / nItemHeight);
		}

		if (index >= sSignation.length) {
			index = sSignation.length - 1;
		} else if (index < 0) {
			index = 0;
		}
		if (event.getAction() == MotionEvent.ACTION_DOWN
				|| event.getAction() == MotionEvent.ACTION_MOVE) {
			bTouch = true;
			if (mSectionIndexer == null) {
				mSectionIndexer = (SectionIndexer) mListView.getAdapter();
			}
			int position = mSectionIndexer.getPositionForSection(index);
			if (position == -1) {
				return true;
			}
			mListView.setSelection(position);
		} else if(event.getAction() == MotionEvent.ACTION_UP) {
			bTouch = false;
			invalidate();
		}
		
		return true;
	}

	private String sSignation[] = { " ", "!", "+", "A", "B", "C", "D", "E", "F",
			"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
			"T", "U", "V", "W", "X", "Y", "Z", "#" };

}
